import  { useEffect, useState } from "react";
import { pokerOptions } from "../api";
import { Button, Card, message, Table, Tooltip, Modal } from "antd";
import RankingAward from "./RankingAward";
import { useLocation } from "react-router-dom";
import { pokerUserActivatInfoC, pokerUserActivatInfoI, userById } from "@/service";
import { getTimeDifference } from "@/utils";
import { QuestionCircleFilled } from '@ant-design/icons';
import guiZerImageUrl from '@/assets/pokerImage/dezhoupuke.png';
export const ActiveDetail = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const location = useLocation();
  const [jetton, setJetton] = useState(0);
  const [qqInfo, setQQInfo] = useState('');
  const [countDown, setCountDown] = useState<any>(); // 24 小时的秒数
  let timer: any = null;

  const [rankList, setRankList] = useState<any[]>([])
  const [cardInfo, setCardInfo] = useState<{
    taskId: string;
    activateId: string;
  }>({
    taskId: '',
    activateId: ''
  })
  const [updatePoker, setUpdatePoker] = useState<any>(0);
  const [surplusPoker, setSurplusPoker] = useState<any>(0);
  const [noticePokerList, setNoticePokerList] = useState<any>([]);
  const [playerPokerList, setPlayerPokerList] = useState<any>([]);
  const [activeMaxChage, setactiveMaxChage] = useState<any>(0);
  const [changePokerBaseNum, setchangePokerBaseNum] = useState<any>(0);
  const [changePokerAddNum, sechangePokerAddNum] = useState<any>(0);
  const [randomPayNum, setpayNum] = useState<any>(0);
  const [userName, setUserName] = useState<any>(0);

  const [open, setOpen] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);

    const showModal = () => {
      setIsModalVisible(true);
    };

    const handleOk = () => {
      setIsModalVisible(false);
    };

    const handleCancel = () => {
      setIsModalVisible(false);
    };
  useEffect(() => {
    (async () => {
    //   pathname: "/activeDetail",
    //     search: `?id=${item.id}&taskId=${item?.taskId}&pubPoker1=${item?.pubPoker1}&pubPoker2=${item?.pubPoker2}&endTime=${item?.endTime}
    //   &activeName=${item?.name}&activeMaxChage=${item?.activeMaxChage}&changePokerBaseNum=${item?.changePokerBaseNum}&changePokerAddNum=${item?.changePokerAddNum}`,
    // });
      // 解析查询参数
      const queryParams = new URLSearchParams(location.search);
      const id = queryParams.get('id'); // 获取单个参数
      const taskId = queryParams.get('taskId');
      const pubPoker1 = queryParams.get('pubPoker1');
      const pubPoker2 = queryParams.get('pubPoker2');
      const endTime = queryParams.get('endTime');
      const activeName = queryParams.get('activeName');
      const activeMaxChage = queryParams.get('activeMaxChage'); //最大换牌
      const changePokerBaseNum = queryParams.get('changePokerBaseNum');//基础所需便便
      const changePokerAddNum = queryParams.get('changePokerAddNum');//增加所需便便

      const image1 = await import(`../../assets/pokerImage/${pubPoker1}.png`)
      const image2 = await import(`../../assets/pokerImage/${pubPoker2}.png`)
      setNoticePokerList([image1, image2])
      setCountDown(getTimeDifference(endTime))
      setQQInfo(activeName || '')
      setactiveMaxChage(activeMaxChage)
      setchangePokerBaseNum(changePokerBaseNum)
      sechangePokerAddNum(changePokerAddNum)

      setCardInfo({
        taskId: taskId || '',
        activateId: id || '',
      })

      if (id && taskId) {
        getInfoDetail({ activateId: id, taskId })
      }
    })()

  }, [location.search]);


  useEffect(()=>{
    getuserById()
  },[])

  const getuserById = async () => {
    const res = await userById()
    console.log(res);
    setUserName(res?.username||0)
  }


  const getInfoDetail = async (item: {
    taskId: string;
    activateId: string;
  }) => {
    const { userActivatInfoList, userAcInfo, total } = await pokerUserActivatInfoI(item)
    setRankList(userActivatInfoList || [])
    setJetton(total || 0)
    setUpdatePoker(userAcInfo?.randomFreeNum || 0)
    setSurplusPoker(userAcInfo?.randomNum || 0)
    setpayNum(userAcInfo?.randomPayNum || 0)

    const image1 = await import(`../../assets/pokerImage/${userAcInfo?.poker1}.png`)
    const image2 = await import(`../../assets/pokerImage/${userAcInfo?.poker2}.png`)
    const image3 = await import(`../../assets/pokerImage/${userAcInfo?.poker3}.png`)
    setPlayerPokerList([image1, image2, image3])
  }

  // const initData = async () => {
  //   setCountDown(60);
  // };
  // useEffect(() => {
  //   initData();
  // }, []);
  useEffect(() => {
    if (!countDown) return;
    clearInterval(timer);
    timer = setInterval(() => {
      setCountDown((prevCountDown: number) => {
        if (prevCountDown === 0) {
          clearInterval(timer); // 倒计时结束，清除定时器
          return 0;
        }
        return prevCountDown - 1; // 每秒减少 1 秒
      });
    }, 1000);

    // 清理定时器
    return () => clearInterval(timer);
  }, [countDown]);

  // 格式化倒计时为 HH:mm:ss
  const formatTime = (seconds: number) => {
    if (!seconds) return "00:00:00";
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    return `${String(h).padStart(2, "0")}:${String(m).padStart(
      2,
      "0"
    )}:${String(s).padStart(2, "0")}`;
  };

  const changeCard = async (num: number, type: 1 | 2) => {
    const res = await pokerUserActivatInfoC({
      ...cardInfo,
      cardNum: num || 0,
      type
    })
    if (res === '换牌成功') {
      messageApi.success('换牌成功')
      getInfoDetail(cardInfo)
    }
  }

  const columns: any = [
    {
      title: "当前排名",
      dataIndex: "rank",
      key: "rank",
      align: "center",
    },
    {
      title: "玩家",
      dataIndex: "userName",
      key: "userName",
      align: "center",
    },
    {
      title: "牌型",
      dataIndex: "pokerType",
      key: "pokerType",
      align: "center",
    },
  ];

  const selectRankingAward = () => {
    setOpen(true);
  };
  return (
    <>
      <div className="activeDetail">
        {contextHolder}
        {/* <div className="selectRankingAward" onClick={selectRankingAward}>
          <Tooltip title="查看排名奖励">
            <svg
              t="1744458802345"
              class="icon"
              viewBox="0 0 1066 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="1504"
              width="200"
              height="200"
            >
              <path
                d="M933.12 736l-115.626667-199.68a298.666667 298.666667 0 1 0-525.653333 0l-115.626667 199.68a42.666667 42.666667 0 0 0 37.12 64h122.453334l62.293333 104.96a42.666667 42.666667 0 0 0 7.68 9.386667 42.666667 42.666667 0 0 0 29.44 11.946666h5.973333a42.666667 42.666667 0 0 0 31.146667-20.906666L554.666667 763.733333l82.346666 142.933334a42.666667 42.666667 0 0 0 31.146667 20.48h5.973333a42.666667 42.666667 0 0 0 29.866667-11.946667 37.12 37.12 0 0 0 7.253333-8.96l62.293334-104.96H896a42.666667 42.666667 0 0 0 37.12-21.333333 42.666667 42.666667 0 0 0 0-43.946667z m-498.346667 65.28l-37.973333-63.573333a42.666667 42.666667 0 0 0-36.266667-20.906667H286.72l61.013333-105.813333a298.666667 298.666667 0 0 0 152.32 78.506666l-65.28 111.786667zM554.666667 608a213.333333 213.333333 0 1 1 0-426.666667 213.333333 213.333333 0 0 1 0 426.666667z m194.133333 108.8a42.666667 42.666667 0 0 0-36.266667 20.906667l-37.973333 63.573333-64.853333-113.066667a301.226667 301.226667 0 0 0 151.893333-78.506666l61.013333 105.813333-73.813333 1.28z"
                fill="#42526E"
                p-id="1505"
              ></path>
            </svg>
          </Tooltip>
        </div> */}
        <div className="header">
          <Card>
            <div className="headerInfo">
              <div>活动便便池：{jetton}</div>
              <div>{qqInfo}</div>
              <div>活动结束倒计时：{formatTime(countDown)}</div>
            </div>
          </Card>
        </div>
        <div className="content">
          <Card
            title={
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                排名
                <div
                  className="selectRankingAward"
                  onClick={selectRankingAward}
                >
                  <Tooltip title="查看排名奖励">
                    <svg
                      className="icon"
                      viewBox="0 0 1066 1024"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      p-id="1504"
                      width="20"
                      height="20"
                    >
                      <path
                        d="M933.12 736l-115.626667-199.68a298.666667 298.666667 0 1 0-525.653333 0l-115.626667 199.68a42.666667 42.666667 0 0 0 37.12 64h122.453334l62.293333 104.96a42.666667 42.666667 0 0 0 7.68 9.386667 42.666667 42.666667 0 0 0 29.44 11.946666h5.973333a42.666667 42.666667 0 0 0 31.146667-20.906666L554.666667 763.733333l82.346666 142.933334a42.666667 42.666667 0 0 0 31.146667 20.48h5.973333a42.666667 42.666667 0 0 0 29.866667-11.946667 37.12 37.12 0 0 0 7.253333-8.96l62.293334-104.96H896a42.666667 42.666667 0 0 0 37.12-21.333333 42.666667 42.666667 0 0 0 0-43.946667z m-498.346667 65.28l-37.973333-63.573333a42.666667 42.666667 0 0 0-36.266667-20.906667H286.72l61.013333-105.813333a298.666667 298.666667 0 0 0 152.32 78.506666l-65.28 111.786667zM554.666667 608a213.333333 213.333333 0 1 1 0-426.666667 213.333333 213.333333 0 0 1 0 426.666667z m194.133333 108.8a42.666667 42.666667 0 0 0-36.266667 20.906667l-37.973333 63.573333-64.853333-113.066667a301.226667 301.226667 0 0 0 151.893333-78.506666l61.013333 105.813333-73.813333 1.28z"
                        fill="#42526E"
                        p-id="1505"
                      ></path>
                    </svg>
                  </Tooltip>
                </div>
              </div>
            }
            className="contentLeft"
          >
            <Table
              rowKey={(record, index) => record.id + index + ''}
              dataSource={rankList}
              columns={columns}
              pagination={false}
              onRow={(record) => {
                if (record.userName === userName) {
                  return {
                    style: { background: '#00BFFF', color: 'black' }, // 红色背景+白色字体
                  };
                }
                return {};
              }}
            />
          </Card>
          <Card className="contentRight">
            <Card title="公共牌池" className="noticePoker" extra={
            <span style={{ marginLeft: '10px', cursor: 'pointer', fontSize: '16px' }} onClick={showModal}>
              <QuestionCircleFilled style={{ fontSize: '24px', marginRight: '5px' }} />
            </span>        }>
          <Modal
            title="规则说明"
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
            footer={null}
          >
            <img
              src={guiZerImageUrl} // 替换为你想显示的图片路径
              alt="说明图"
              style={{ width: '100%',height:'auto' }}
            />
          </Modal>

              <div className="noticePokerList">
                {noticePokerList.map((item: any, index: number) => (
                  <img key={index} src={item?.default} alt="" />
                ))}
              </div>
            </Card>
            <Card title="玩家手牌" className="playerPoker">
              <div className="playerPokerList">
                {playerPokerList.map((item: any, index: number) => {
                  return (
                    <div key={index} className="playerPokerItem">
                      <img src={item?.default} alt="" />
                      <Button onClick={() => changeCard(index + 1, 1)}>换牌</Button>
                    </div>
                  )
                })}
              </div>
            </Card>
            <Card className="action">
              <Button onClick={() => changeCard(0, 2)}>更换所有手牌</Button>
              <span>免费换牌剩余次数：{updatePoker}</span>
              <span>已换牌次数：{surplusPoker}</span>
              <span>最大换牌次数：{activeMaxChage}</span>
              <span>换牌所需便便（免费次数未耗尽不消耗便便）：{randomPayNum * changePokerAddNum + (changePokerBaseNum-0)}</span>

            </Card>
          </Card>
        </div>
      </div>
      <RankingAward open={open} setOpen={setOpen}
        activateId={cardInfo?.activateId} />
    </>
  );
};

export default ActiveDetail;
